import 'package:flutter/cupertino.dart';
import 'package:kq_flutter_tv_widgets/widgets/update/update_view.dart';
import 'package:kq_flutter_core_widget/utils/contact.dart';

import '../divider/kq_divider.dart';

///分屏界面。
class SplitView extends StatefulWidget {
  ///左边界面。
  final Widget parent;

  ///控制器，所有操作均在控制器内进行。
  final SplitViewController? controller;

  ///获取控制器。
  final Function(SplitViewController controller)? getController;

  const SplitView({
    super.key,
    required this.parent,
    this.controller,
    this.getController,
  });

  @override
  State<StatefulWidget> createState() => _SplitViewState();
}

class _SplitViewState extends State<SplitView> {
  late SplitViewController _controller;
  Widget? _child;
  UpdateViewState? _updateViewState;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? SplitViewController();
    _controller._state = this;
    widget.getController?.call(_controller);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: widget.parent),
              const KqVerticalDivider(),
              Expanded(
                child: UpdateView(
                  build: (updateViewState) {
                    _updateViewState = updateViewState;
                    return _child ?? Container();
                  },
                ),
              ),
            ],
          ),
        )
      ],
    );
  }
}

class SplitViewController extends Contact {
  _SplitViewState? _state;

  ///打开左边界面[page]。
  ///传递参数[arguments]。
  ///设置回调[callback]。
  open(
    Widget page, {
    dynamic arguments,
    Function(dynamic result)? callback,
  }) {
    parentArguments = arguments;
    if (callback != null) {
      parentCallback = callback;
    }
    childCallback?.call(parentArguments);
    _state?._child = page;
    _state?._updateViewState?.update();
  }

  ///关闭右边界面。
  ///回传参数[result]。
  close({
    dynamic result,
  }) {
    childArguments = result;
    parentCallback?.call(childArguments);
    _state?._child = null;
    _state?._updateViewState?.update();
  }
}
